package com.fxu.framework.core.util;

import cn.hutool.crypto.asymmetric.RSA;
import com.fxu.framework.core.exception.MsgException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 非对称 RSA 加密解密工具类
 * @author fangxu
 * @version 2022-06-05
 */
@Slf4j
public class RSAUtil {

//    public static void main(String[] args) {
//        RSA rsa = new RSA();
//        String publicKey = rsa.getPublicKeyBase64();
//        String privateKey = rsa.getPrivateKeyBase64();
//        System.out.println("publicKey=" + publicKey);
//        System.out.println("privateKey=" + privateKey);
//        String encryptStr = RSAUtil.encrypt(publicKey, "123456");
//        String decryptStr = RSAUtil.decrypt(privateKey, encryptStr);
//        System.out.println(decryptStr);
//    }

    /**
     * RSA公钥加密
     *
     * @param publicKey 公钥
     * @param str       加密字符串
     * @return 密文
     */
    public static String encrypt(String publicKey, String str) {
        try {
            //base64编码的公钥
            byte[] decoded = Base64.decodeBase64(publicKey);
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                    .generatePublic(new X509EncodedKeySpec(decoded));
            //RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return Base64.encodeBase64String(cipher.doFinal(str.getBytes("gbk")));
        } catch (Exception e) {
            log.error("rsa decrypt error!", e);
            // throw new MsgException("rsa decrypt error");
            return null;
        }
    }

    /**
     * RSA私钥解密
     *
     * @param privateKey 私钥
     * @param str        加密字符串
     * @return 铭文
     */
    public static String decrypt(String privateKey, String str) {
        try {
            //64位解码加密后的字符串
            byte[] inputByte = Base64.decodeBase64(str.getBytes("gbk"));
            //base64编码的私钥
            byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                    .generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            return new String(cipher.doFinal(inputByte));
        } catch (Exception e) {
            log.error("rsa decrypt error!", e);
            // throw new MsgException("rsa decrypt error");
            return null;
        }
    }
}